package service

import (
	"database/sql"
	"fmt"
	"gitee.com/cdsailyj/go-vpn/initialize"
	"strings"
)

type OfficeService struct{}

type SysOffice struct {
	ID         string         `db:"ID" json:"ID" form:"ID"`
	NAME       sql.NullString `db:"NAME" json:"NAME" form:"NAME"`
	PARENT_ID  sql.NullString `db:"PARENT_ID" json:"PARENT_ID" form:"PARENT_ID"`
	PARENT_IDS sql.NullString `db:"PARENT_IDS" json:"PARENT_IDS" form:"PARENT_IDS"`
}

// 所有公司
func (t *OfficeService) GetOfficeMap() (map[string]string, error) {
	mapData := make(map[string]string)
	dbXtk, _ := initialize.GetXtkDB()
	var offices []SysOffice
	sqlString3 := fmt.Sprintf(`SELECT ID, NAME, PARENT_ID, PARENT_IDS   FROM  SYS_OFFICE WHERE DEL_FLAG = '0'`)
	err := dbXtk.Select(&offices, sqlString3)
	if err != nil {
		return mapData, err
	}
	for _, v := range offices {
		mapData[v.ID] = v.NAME.String
	}
	return mapData, nil
}

// 查询单位层级
func (t *OfficeService) GetOfficeLevelName(id string) []SysOffice {
	dbXtk, _ := initialize.GetXtkDB()
	var office SysOffice
	var levels []SysOffice

	sqlString3 := fmt.Sprintf(`SELECT ID, NAME, PARENT_ID, PARENT_IDS   FROM  SYS_OFFICE WHERE ID = :1 OFFSET 0  ROWS FETCH NEXT 1 ROWS ONLY `)
	err := dbXtk.Get(&office, sqlString3, id)
	if err != nil || !office.PARENT_IDS.Valid {
		fmt.Printf("公司查询错误：%#v \t %#v \n", id, err)
		return levels
	}

	parentIds := strings.Split(office.PARENT_IDS.String, ",")[2:]
	idStr := strings.Join(parentIds, "' , '")
	var parents []SysOffice
	sqlString4 := fmt.Sprintf(`SELECT ID, NAME, PARENT_ID, PARENT_IDS   FROM  SYS_OFFICE WHERE ID IN('%s')`, idStr)
	err = dbXtk.Select(&parents, sqlString4)
	if err != nil {
		fmt.Printf("父级单位查询错误：%#v \t %#v \n", id, err)
		return levels
	}
	parentMap := make(map[string]SysOffice)
	for _, v := range parents {
		parentMap[v.ID] = v
	}

	for _, pid := range parentIds {
		levels = append(levels, parentMap[pid])
	}
	levels = append(levels, office)

	return levels
}
